package com.ptrans.server;

import static com.ptrans.utilities.CommonUtilities.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.w3c.dom.Node;

import android.content.Context;
import android.util.Log;

import com.ptrans.R;
import com.ptrans.modele.User;
import com.ptrans.utilities.CommonUtilities;
import com.ptrans.utilities.ParserXML;

/**
 * Class allowing to send a a push message to users.
 * @author Jean
 *
 */
public class SendHandler {

	private static final int MAX_ATTEMPTS = 5;
    private static final int BACKOFF_MILLI_SECONDS = 2000;
    private static final Random random = new Random();
    
    public static void sendAll(final Context context, User user, String msg) {
        Log.i(TAG, "Send a message to all device : " + msg + ")");
        String serverUrl = SERVER_URL;
        Node response;
        String message;
        Map<String, String> params = new HashMap<String, String>();
        String msgFinal = CommonUtilities.encodeMessageUrl(msg);
        params.put("c", "MessageController");
        params.put("a", "sendAll");
        params.put(PARAM_SENDER, user.getRegId());
        params.put(PARAM_MESSAGE, msgFinal);
        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
        // Once GCM returns a registration id, we need to register it in the
        // demo server. As the server might be down, we will retry it a couple
        // times.
        for (int i = 1; i <= MAX_ATTEMPTS; i++) {
            Log.d(TAG, "Attempt #" + i + " to register");
            try {
                response = ServerHttp.sendGet(serverUrl, params);
                if(!ParserXML.getState(response).equals("")) {
                	Log.i(TAG, "State response is NOT 0");
                } else {
                	Log.i(TAG, "State response is 0");
                }
                message = ParserXML.getInfo(response);
                CommonUtilities.displayMessage(context, message, CommonUtilities.EXTRA_INFO);
                
                return;
            } catch (IOException e) {
                // Here we are simplifying and retrying on any error; in a real
                // application, it should retry only on unrecoverable errors
                // (like HTTP error code 503).
                Log.e(TAG, "Failed to send on attempt " + i + ":" + e);
                if (i == MAX_ATTEMPTS) {
                    break;
                }
                try {
                    Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                    Thread.sleep(backoff);
                } catch (InterruptedException e1) {
                    // Activity finished before we complete - exit.
                    Log.d(TAG, "Thread interrupted: abort remaining retries!");
                    Thread.currentThread().interrupt();
                    return;
                }
                // increase backoff exponentially
                backoff *= 2;
            }
        }
        message = context.getString(R.string.message_error);
        CommonUtilities.displayMessage(context, message, CommonUtilities.EXTRA_INFO);
        Log.e(TAG, "Failed to connect to server");
    }
	
}
